/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function (root) {
  let ans = [], temp = []
  let queue = [], front = 0, rear = 0, levelPos, depth = 0
  if (root != null) {
    queue[++rear] = root
  }
  levelPos = rear
  while (front < levelPos) {
    const p = queue[++front]
    temp.push(p.val)
    if (p.left != null) queue[++rear] = p.left
    if (p.right != null) queue[++rear] = p.right
    if (front == levelPos) {
      depth++
      if (depth % 2 == 0) {
        ans.push(temp.reverse())
      } else {
        ans.push(temp)
      }
      temp = []
      levelPos = rear
    }
  }
  return ans
}
/**
 * 换个方法，用双端队列
 */
var zigzagLevelOrder2 = function (root) {
  let ans = [], temp = []
  let queue = [], front = 0, rear = 0, levelPos, isleft2right = true
  if (root != null) {
    queue[++rear] = root
  }
  levelPos = rear
  while (front < levelPos) {
    const p = queue[++front]
    if (isleft2right) {
      temp.push(p.val)
    } else {
      temp.unshift(p.val)
    }
    if (p.left != null) queue[++rear] = p.left
    if (p.right != null) queue[++rear] = p.right
    if (front == levelPos) {
      ans.push(temp)
      temp = []
      levelPos = rear
      isleft2right = !isleft2right
    }
  }
  return ans
}